import { Card, Col, Row, Typography, Table, Button, Space, message, Modal, Form, Input, Select, Tag, Switch } from "antd";
import type { ColumnsType } from "antd/es/table";
import { useEffect, useState,useMemo } from "react";
import { Iconify } from "@/components/icon";
import dayjs from 'dayjs';
import { debounce } from 'lodash';
import { User } from "src/type/user";
import { UserRole } from "src/type/role";


declare global {
	interface Window {
		electronAPI: ElectronAPI;
	}
}

function UserAccountTable() {
	const [users, setUsers] = useState<User[]>([]);
	const [loading, setLoading] = useState(false);
	const [isModalOpen, setIsModalOpen] = useState(false);
	const [currentUser, setCurrentUser] = useState<User | null>(null);
	const [form] = Form.useForm();
	const [filteredUsers, setFilteredUsers] = useState<User[]>([]);
	const [isSearching, setIsSearching] = useState(false);
	const [searchKeyword, setSearchKeyword] = useState('');
	const [roles, setRoles] = useState<UserRole[]>([
		{ name: 'admin', permission: ['dashboard', 'patients', 'settings'] },
		{ name: 'doctor', permission: ['dashboard', 'patients'] },
		{ name: 'nurse', permission: ['patients'] },
		{ name: 'user', permission: [] }
	]);

// 只存储角色名称
	const [currentRoleName, setCurrentRoleName] = useState('user');

// 获取完整的角色对象（按需计算）
	const currentRole = useMemo(() => {
		return roles.find(role => role.name === currentRoleName) || roles[0];
	}, [currentRoleName, roles]);

	useEffect(() => {
		fetchUsers();
	}, []);

	const fetchUsers = async () => {
		setLoading(true);
		try {
			const data = await window.electronAPI.ipcRenderer.invoke('read-users');
			setUsers(data);
			setFilteredUsers(data);
		} catch (error) {
			console.error('Error fetching users:', error);
			message.error('Failed to fetch users');
		} finally {
			setLoading(false);
		}
	};

	const showAddModal = () => {
		setCurrentUser(null);
		form.resetFields();
		setIsModalOpen(true);
	};

	const showEditModal = (user: User) => {
		setCurrentUser(user);
		form.setFieldsValue({
			...user,
			role: user.role?.name || 'user', // 只设置role的name属性
			createdAt: user.createdAt ? dayjs(user.createdAt) : null,
			updatedAt: user.updatedAt ? dayjs(user.updatedAt) : null
		});
		setIsModalOpen(true);
	};

	const handleSubmit = async () => {
		try {
			const values = await form.validateFields();
			console.log('表单原始值:', values); // 调试日志

			// 规范化角色数据
			const normalizeRole = (roleInput: any): UserRole => {
				if (!roleInput) return { name: 'user', permission: [] };
				if (typeof roleInput === 'string') {
					// 处理从Select组件返回的字符串值
					return { name: roleInput, permission: [] };
				}
				if (roleInput.name) return roleInput;
				return { name: 'user', permission: [] };
			};

			const userData = {
				...values,
				role: normalizeRole(values.role),  // 使用规范化函数
				permissions: Array.isArray(values.permissions) ? values.permissions : [],
				createdAt: values.createdAt ?
					values.createdAt.format('YYYY-MM-DD') :
					new Date().toISOString(),
				updatedAt: new Date().toISOString(),
				isActive: Boolean(values.isActive)
			};

			console.log('处理后用户数据:', userData); // 调试日志

			if (currentUser) {
				// 更新现有用户
				const updateData = {
					...userData,
					id: currentUser.id,
					// 确保密码只在修改时更新
					password: values.password || undefined
				};
				console.log('更新用户数据:', updateData);
				await window.electronAPI.ipcRenderer.invoke('update-user', updateData);
				message.success('User updated successfully');
			} else {
				// 创建新用户
				if (!values.password) {
					throw new Error('Password is required for new users');
				}
				console.log('创建用户数据:', userData);
				await window.electronAPI.ipcRenderer.invoke('create-user', userData);
				message.success('User added successfully');
			}

			setIsModalOpen(false);
			await fetchUsers(); // 等待刷新数据
		} catch (error: any) {
			console.error('保存用户错误:', error);
			message.error(error.message || 'Failed to save user');
		}
	};


	const performSearch = async (keyword: string) => {
		try {
			setIsSearching(true);
			if (!keyword.trim()) {
				setFilteredUsers(users);
				return;
			}

			const results = await window.electronAPI.ipcRenderer.searchUsers(keyword);
			setFilteredUsers(results);
		} catch (error) {
			console.error('Search error:', error);
			message.error('Search failed');
		} finally {
			setIsSearching(false);
		}
	};

	const debouncedSearch = debounce(performSearch, 300);

	const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
		const keyword = e.target.value;
		setSearchKeyword(keyword);

		if (!keyword.trim()) {
			setFilteredUsers(users);
			return;
		}

		debouncedSearch(keyword);
	};

	const handleSearch = () => {
		performSearch(searchKeyword);
	};

	const handleDeleteUser = async (id: string) => {
		Modal.confirm({
			title: 'Confirm Deletion',
			content: 'Are you sure you want to delete this user?',
			okText: 'Delete',
			okType: 'danger',
			cancelText: 'Cancel',
			onOk: async () => {
				try {
					await window.electronAPI.ipcRenderer.invoke('delete-user', id);
					message.success('User deleted successfully');
					fetchUsers();
				} catch (error) {
					console.error('Error deleting user:', error);
					message.error('Failed to delete user');
				}
			}
		});
	};



	const handleStatusChange = async (user: User, checked: boolean) => {
		try {
			// 确保包含所有必要字段
			const updateData = {
				...user, // 包含现有所有字段
				isActive: checked,
				updatedAt: new Date().toISOString(),
				permissions: user.permissions || [] // 确保permissions不为空
			};

			await window.electronAPI.ipcRenderer.invoke('update-user', updateData);
			message.success(`用户已${checked ? '启用' : '禁用'}`);
			await fetchUsers();
		} catch (error: any) {
			// console.error('状态更新失败:', error);
			message.error(error.message ||'状态更新失败');
		}
	};



	const columns: ColumnsType<User> = [
		{
			title: 'Username',
			dataIndex: 'username',
			key: 'username',
			render: (text) => <Typography.Text strong>{text}</Typography.Text>,
		},
		{
			title: 'Name',
			dataIndex: 'name',
			key: 'name',
		},
		{
			title: 'Email',
			dataIndex: 'email',
			key: 'email',
		},
		{
			title: 'Role',
			dataIndex: 'role',
			key: 'role',
			render: (role: UserRole | string | undefined) => {
				// 处理 role 为 undefined 的情况
				if (!role) {
					return <Tag color="default">UNKNOWN</Tag>;
				}

				// 处理 role 是字符串的情况（可能是数据库返回的 JSON 字符串）
				if (typeof role === 'string') {
					try {
						role = JSON.parse(role) as UserRole;
					} catch {
						return <Tag color="default">INVALID</Tag>;
					}
				}

				// 确保 role 对象有 name 属性
				const roleName = role.name || 'unknown';

				return (
					<Tag color={
						roleName === 'admin' ? 'red' :
							roleName === 'doctor' ? 'blue' : 'green'
					}>
						{roleName.toUpperCase()}
					</Tag>
				);
			},
		},
		{
			title: 'Status',
			dataIndex: 'isActive',
			key: 'isActive',
			render: (isActive, record) => (
				<Switch
					checked={isActive}
					onChange={(checked) => handleStatusChange(record, checked)}
				/>
			),
		},
		{
			title: 'Created',
			dataIndex: 'createdAt',
			key: 'createdAt',
			render: (date) => date ? new Date(date).toLocaleDateString() : '-',
		},
		{
			title: 'Last Updated',
			dataIndex: 'updatedAt',
			key: 'updatedAt',
			render: (date) => date ? new Date(date).toLocaleDateString() : '-',
		},
		{
			title: 'Action',
			key: 'action',
			render: (_, record) => (
				<Space size="middle">
					<Button
						type="primary"
						ghost
						onClick={() => showEditModal(record)}
					>
						Edit
					</Button>
					<Button
						danger
						onClick={() => handleDeleteUser(record.id)}
					>
						Delete
					</Button>
				</Space>
			),
		},
	];

	return (
		<div>
			<Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
				<Col span={24}>
					<Card>
						<Space>
							<Typography.Title level={4} style={{ margin: 0 }}>
								User Management
							</Typography.Title>
							<Input.Search
								placeholder="Search by username, name or email..."
								enterButton="Search"
								size="middle"
								value={searchKeyword}
								onChange={handleSearchChange}
								onSearch={handleSearch}
								loading={isSearching}
								style={{ width: 350 }}
							/>
							<Button
								type="primary"
								onClick={showAddModal}
								icon={<Iconify icon="ic:baseline-plus" />}
							>
								Add User
							</Button>
						</Space>
					</Card>
				</Col>
			</Row>

			<Row gutter={[16, 16]}>
				<Col span={24}>
					<Card>
						<Table
							columns={columns}
							dataSource={filteredUsers}
							loading={loading || isSearching}
							rowKey="id"
							bordered
							scroll={{ x: true }}
						/>
					</Card>
				</Col>
			</Row>

			<Modal
				title={currentUser ? "Edit User" : "Add New User"}
				open={isModalOpen}
				onOk={handleSubmit}
				onCancel={() => setIsModalOpen(false)}
				okText={currentUser ? "Update" : "Create"}
				cancelText="Cancel"
				width={700}
			>
				<Form
					form={form}
					layout="vertical"
					initialValues={{
						isActive: true
					}}
				>
					<Row gutter={16}>
						<Col span={12}>
							<Form.Item
								name="username"
								label="Username"
								rules={[{ required: true, message: 'Please input username!' }]}
							>
								<Input placeholder="Username" />
							</Form.Item>
						</Col>
						<Col span={12}>
							<Form.Item
								name="email"
								label="Email"
								rules={[
									{ required: true, message: 'Please input email!' },
									{ type: 'email', message: 'Please input valid email!' }
								]}
							>
								<Input placeholder="Email" />
							</Form.Item>
						</Col>
					</Row>

					<Row gutter={16}>
						<Col span={12}>
							<Form.Item
								name="name"
								label="Full Name"
								rules={[{ required: true, message: 'Please input full name!' }]}
							>
								<Input placeholder="Full name" />
							</Form.Item>
						</Col>
						<Col span={12}>
							<Form.Item
								name="phone"
								label="Phone"
							>
								<Input placeholder="Phone number" />
							</Form.Item>
						</Col>
					</Row>

					{!currentUser && (
						<Row gutter={16}>
							<Col span={12}>
								<Form.Item
									name="password"
									label="Password"
									rules={[{ required: true, message: 'Please input password!' }]}
								>
									<Input.Password placeholder="Password" />
								</Form.Item>
							</Col>
							<Col span={12}>
								<Form.Item
									name="confirmPassword"
									label="Confirm Password"
									dependencies={['password']}
									rules={[
										{ required: true, message: 'Please confirm password!' },
										({ getFieldValue }) => ({
											validator(_, value) {
												if (!value || getFieldValue('password') === value) {
													return Promise.resolve();
												}
												return Promise.reject(new Error('The two passwords do not match!'));
											},
										}),
									]}
								>
									<Input.Password placeholder="Confirm password" />
								</Form.Item>
							</Col>
						</Row>
					)}

					<Row gutter={16}>
						<Col span={12}>
							<Form.Item
								name="role"
								label="Role"
								rules={[{ required: true, message: 'Please select role!' }]}
							>
								<Select
									placeholder="Select role"
									value={currentRoleName} // 只保存 name 字符串
									onChange={(value: string) => {
										console.log('---------- onChange 触发 ----------');
										console.log('1. 用户选择的value值:', value); // 这里会打印用户实际选择的值
										console.log('2. 改变前的currentRoleName:', currentRoleName); // 改变前的状态值
										if (!['admin', 'doctor', 'nurse', 'user'].includes(value)) {
											console.error('非法的角色值:', value);
											return;
										}
										setCurrentRoleName(value as 'admin' | 'doctor' | 'nurse' | 'user');
									}}
								>
									{roles.map(role => (
										<Select.Option key={role.name}>
											{role.name.toUpperCase()}
										</Select.Option>
									))}
								</Select>

							</Form.Item>
						</Col>
						<Col span={12}>
							<Form.Item
								name="isActive"
								label="Active Status"
								valuePropName="checked"
							>
								<Switch />
							</Form.Item>
						</Col>
					</Row>

					<Form.Item
						name="about"
						label="About"
					>
						<Input.TextArea rows={3} placeholder="User description" />
					</Form.Item>
				</Form>
			</Modal>
		</div>
	);
}

export default UserAccountTable;
